package com.secsbrain.deploy.web.controller;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.secsbrain.cmdb.client.iface.AppInfoService;
import com.secsbrain.cmdb.client.model.AppDetail;
import com.secsbrain.cmdb.client.model.AppTypeDto;
import com.secsbrain.common.ResponseVo;
import com.secsbrain.deploy.biz.IBuildModelService;
import com.secsbrain.deploy.dal.model.BuildModel;
import com.secsbrain.deploy.utils.command.CommandRunner;
import com.secsbrain.deploy.utils.command.WriteToFileStrategy;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("app")
public class AppController {

    private static final Logger logger = LoggerFactory.getLogger(AppController.class);

    @Autowired
    IBuildModelService buildModelService;

    @Autowired
    AppInfoService appInfoService;

    @Autowired
    private CommandRunner commandRunner;

    //@Resource
    //private IIdUserService idUserService;

    @Value("${server.port}")
    String port;

    @Value("${jdk.image}")
    private String jdkImage;

    @RequestMapping(value = "/test", method = RequestMethod.GET
    )
    public String test() {
        ResponseVo<List<AppTypeDto>> listResponseVo = appInfoService.queryAppType();
        System.out.println(listResponseVo);
//    	String command="/home/test/deploy.sh";
//    	WriteToFileStrategy writeToFileStrategy=new WriteToFileStrategy("/home/logs/command", command, 1);
//    	try {
//			commandRunner.exec(command, writeToFileStrategy);
//		} catch (IOException e) {
//			logger.error("",e);
//		}
        return "success";
    }

    @RequestMapping(value = "/getAppDockerFile/{appName}/{env}", method = RequestMethod.GET)
    public void getAppDockerFile(HttpServletResponse response, @PathVariable("appName") String appName, @PathVariable("env") String env) {
        Assert.hasText(appName, "appName不能为空");
        Assert.hasText(env, "环境名称不能为空");

        BuildModel buildModelParam = new BuildModel();
        buildModelParam.setAppName(appName);
        buildModelParam.setEnv(env);
        BuildModel buildModel = buildModelService.selectOne(buildModelParam);
        Assert.isTrue(buildModel != null, "该应用不存在构建任务");

        Configuration configuration = new Configuration(Configuration.VERSION_2_3_30);
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=Dockerfile");

        try {
            configuration.setClassForTemplateLoading(this.getClass(), "/template");

            String modelJsonStr = buildModel.getModelJson();
            Map<String, Object> modelJsonMap = JSON.parseObject(modelJsonStr, Map.class);

            Map<String, Object> templateParam = new HashMap<>();
            templateParam.put("jdkImage", jdkImage);
            String targetPath = (String) modelJsonMap.get("targetPath");
            templateParam.put("targetPath", targetPath);
            //targetPath如 xib-channel-service/target/xib-channel.jar
            //targetPath2如 xib-channel-service/target/*.jar
            String targetPath2 = targetPath.substring(0, targetPath.lastIndexOf("/") + 1) + "*.jar";
            templateParam.put("targetPath2", targetPath2);

            String jarName = targetPath.substring(targetPath.lastIndexOf("/") + 1);
            templateParam.put("jarName", jarName);

            String jvmOption = (String) modelJsonMap.get("jvmOps");
            String javaOption = (String) modelJsonMap.get("javaOps");

            String[] jvmOptionList = jvmOption.split(" ");
            String[] javaOptionList = javaOption.split(" ");
            templateParam.put("jvmOptionList", jvmOptionList);
            templateParam.put("javaOptionList", javaOptionList);

            Template template = configuration.getTemplate("/Dockerfile_SPRING_BOOT.ftl", "UTF-8");
            template.process(templateParam, response.getWriter());
        } catch (Exception e) {
            logger.error("", e);
        }
    }

    public static void main(String[] args) {
        String targetPath = "xib-channel-service/target/xib-channel.jar";
        String targetPath2 = targetPath.substring(0, targetPath.lastIndexOf("/") + 1) + "*.jar";
        System.out.println(targetPath2);
    }

}
